const express = require('express');
const http = require('http');
const path = require('path');
const reload = require('reload');
const bodyParser = require('body-parser');
const logger = require('morgan');
const request = require('request');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors')

const app = express();

app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));

// 不能使用body-parse中间件，参考：https://blog.csdn.net/weixin_34023982/article/details/93562439
// app.use(bodyParser.json()); // Parses json, multi-part (file), url-encoded

app.use('/public', express.static('public'));
app.use('/pages', express.static('pages'));


app.use(cors())
// app.use(express.urlencoded({extended: false}))

//跨域代理：参考，https://www.ufcn.cn/it/773310.html
// 将/api/的请求代理到http://127.0.0.1:8097/api
// app.use('/api', function (req, res) {
//     let url = 'http://127.0.0.1:8097/api' + req.url;
//     let params = req.body
//     console.log('----【info】----url:',url);
//     console.log('----【info】----req body:',req.body);
//     console.log('----【info】----method:',req.method);
//
//     //pipe 把浏览器的请求数据传给 request 客户端，然后将目标服务器的响应数据传回浏览器
//     req.pipe(request(url,function(error,response,body) {
//         // console.log('response:',response);
//         console.log('代理返回的数据:',body);
//     })).pipe(res);
// });


app.use('/api', createProxyMiddleware({
    // target - 所要代理到的实际接口地址
    // changeOrigin - 如果设置为true,本地会开启node服务接收本地请求并代理请求接口，这样就不会有跨域问题了，仅适用于开发环境
    // pathRewrite -  重新target接口的url地址
    target: 'http://14.103.136.36:8097/api',
    // target: 'http://127.0.0.1:8097/api',
    changeOrigin: true,
    pathRewrite: {
        "^/api":""
    // },
    // cookieDomainRewrite:{
    //     "http://127.0.0.1:8097":"localhost"
    }
}))
app.use('/pyapi', createProxyMiddleware({
    target: 'http://49.234.17.113:5917/pyapi',
    // target: 'http://0.0.0.0:5917/pyapi',
    changeOrigin: true,
    pathRewrite: {
        "^/pyapi":""
    }
}))


app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

const server = http.createServer(app);

// Reload code here
reload(app)
  .then(function (reloadReturned) {
    // reloadReturned is documented in the returns API in the README

    // Reload started, start web server
    server.listen(app.get('port'), function () {
      console.log(
        'Web server listening on port http://localhost:' + app.get('port')
      );
    });
  })
  .catch(function (err) {
    console.error(
      'Reload could not start, could not start server/sample app',
      err
    );
  });
